//
//  CZOAuthViewController.swift
//  Swift -- 微博
//
//  Created by sks on 16/6/26.
//  Copyright © 2016年 mohaha. All rights reserved.
//

import UIKit
import SVProgressHUD
import AFNetworking
class CZOAuthViewController: UIViewController {
    
    override func loadView() {
        view = webView
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        
      setupUI()
    }
    
   private func setupUI() {
    
    view.backgroundColor = UIColor.whiteColor()
    navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", style: UIBarButtonItemStyle.Plain, target: self, action: #selector(CZOAuthViewController.cancelClick))
    navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填充", style: UIBarButtonItemStyle.Plain, target: self, action: #selector(CZOAuthViewController.autoFillClick))
    
    navigationItem.title = "OAuto登录"
    }
    
    //懒加载webView
    private lazy var webView :UIWebView = {
    
        let Wview = UIWebView()
        Wview.delegate = self
        let url = NSURL(string: "https://api.weibo.com/oauth2/authorize?client_id=\(APPKEY)&redirect_uri=\(redirect_uri)")
        
        let requset = NSURLRequest(URL: url!)
        Wview.loadRequest(requset)
        return Wview
    
    }()
    
    //按钮点击事件
    
    @objc private func cancelClick () {
      
       dismissViewControllerAnimated(true, completion: nil)
    
    }
    
    @objc private func autoFillClick () {
    
        let jsString = "document.getElementById('userId').value='15168581791',document.getElementById('passwd').value='ss20090567'"
        
      //JS注入
        webView.stringByEvaluatingJavaScriptFromString(jsString)
    }

}

extension CZOAuthViewController : UIWebViewDelegate {
    
    //将要加载request
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        
       
        
        let  urlString = request.URL?.absoluteString
        
        
        //判断是否有值 而且前缀是否是回调页
        if let u = urlString where u.hasPrefix(redirect_uri) {
            
            //请求键值对
            let query = request.URL?.query
            
            if let q = query {
               
              let code = q.substringFromIndex("code=".endIndex)
                
              loadUserAccount(code)

                
            }
        }
        
        return true
    }
    
    //开始加载
    func webViewDidStartLoad(webView: UIWebView) {
        SVProgressHUD.show()
    }

    //加载完成
    func webViewDidFinishLoad(webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
    
    //加载失败
    func webView(webView: UIWebView, didFailLoadWithError error: NSError?) {
        
    }

}

extension CZOAuthViewController{

    func loadUserAccount(code:String) {
        
        CZNetWorkTools.sharedTools.oauthLoadUserAccount(code, success: { (response)->() in
            
            guard let res = response as? [String:AnyObject] else {
               print("返回的不是一个字典")
              return
            }
            //字典转模型
            let userAccount = CZUserAccount(dict: res)
            self.loadUserInfo(userAccount)
            
            }) { (error)->() in
                print(error)
        }
    }
    
    func loadUserInfo(userAccount:CZUserAccount) {
        CZNetWorkTools.sharedTools.oauthLoadUserInfo(userAccount, success: { (response) in
            //判断是否有值 是不是字典类型
            guard let res = response as?[String : AnyObject] else{
              
               return
            }
            userAccount.avater_large = res["avatar_large"] as? String
            userAccount.screen_name = res["screen_name"] as? String
            
            //通过单例工具类 归档保存数据
            CZUserAccountTools.sharedTools.saveUserAccount(userAccount)
            
            }) { (error) in
                
                print("失败\(error)")
        }
        
    }


}


